package main

import (
	"fmt"
	"net/http"
	"html/template"
	"strings"
	"time"
	"log"
	"io"
	"strconv"
	"crypto/md5"
)

func sayHelloName(w http.ResponseWriter,r *http.Request){
	r.ParseForm()//parse parameters
	fmt.Println("--------------------------------------------")
	fmt.Println(r.Form)
	fmt.Println("path", r.URL.Path)
    fmt.Println("scheme", r.URL.Scheme)
    fmt.Println(r.Form["url_long"])
	for k,v:=range r.Form {
		fmt.Println("key: ",k)
		fmt.Println("val: ",strings.Join(v," "))
	}
	fmt.Fprintf(w, "Hello! Let's test cross site script.")
}

func form(w http.ResponseWriter,r *http.Request){
	fmt.Println("--------------------------------------------")
	fmt.Println("Request Method: ",r.Method)
	fmt.Println("Form data: ",r.Form)
	if r.Method=="GET" {
		curtime:=time.Now().Unix()
		h:=md5.New()
		io.WriteString(h,strconv.FormatInt(curtime,10))
		token:=fmt.Sprintf("%x",h.Sum(nil))
		
		t,_:=template.ParseFiles("multisubmit.gtpl")
		t.Execute(w,token)
	}else{
		r.ParseForm()
		token:=r.Form.Get("token")
		if token!="" {
			fmt.Println("toekn: ",token)
		}else{
			fmt.Println("token not exist, error!!!")
		}
		
		fmt.Println("username: ",template.HTMLEscapeString(r.Form.Get("username")))
		fmt.Println("password: ",template.HTMLEscapeString(r.Form.Get("password")))
		fmt.Println("interest: ",template.HTMLEscapeString(r.Form.Get("interest")))
		fmt.Println("gender: ",template.HTMLEscapeString(r.Form.Get("gender")))
		fmt.Println("fruit: ",template.HTMLEscapeString(r.Form.Get("fruit")))

		fmt.Fprintf(w,"username: %v\n",template.HTMLEscapeString(r.Form.Get("username")))
		fmt.Fprintf(w,"password: %v\n",template.HTMLEscapeString(r.Form.Get("password")))
		fmt.Fprintf(w,"interest: %v\n",template.HTMLEscapeString(r.Form.Get("interest")))
		fmt.Fprintf(w,"gender:   %v\n",template.HTMLEscapeString(r.Form.Get("gender")))
		fmt.Fprintf(w,"fruit:    %v\n",template.HTMLEscapeString(r.Form.Get("fruit")))
		fmt.Fprintf(w,"token:    %v\n",template.HTMLEscapeString(r.Form.Get("token")))
	}
}

func main(){
	http.HandleFunc("/",sayHelloName)
	http.HandleFunc("/form",form)
	er:=http.ListenAndServe(":9090",nil)
	if er!=nil{
		log.Fatal("ListenAndServe",er)
	}
}